package au.com.zonski.gwlite.j2me.client;

import net.jscience.math.kvm.MathFP;

public class BulletController implements Controller {

	private boolean bounce;
	private int speed;
	
	public BulletController( boolean bounce, int speed )
	{
		this.bounce = bounce;
		this.speed = speed;
	}
	
	public void reset() 
	{
	}

	public boolean update(GWLiteCanvas gameState, GWEntity o) 
	{
		int[] controllerData = (int[]) o.controllerData;
		if( controllerData == null )
		{
			int angle = Math.abs( gameState.random.nextInt() % (MathFP.PI * 2) );
			int dx = MathFP.mul( MathFP.cos( angle ), this.speed );
			int dy = MathFP.mul( MathFP.sin( angle ), this.speed );
			controllerData = new int[]{ 0, dx, dy };
			o.controllerData = controllerData;
		}
		o.x += controllerData[1];
		o.y += controllerData[2];
		int wall = gameState.enforceBounds(o);
		boolean dead;
		if( wall != 0 )
		{
			if( !this.bounce )
			{
				// add some animation
				dead = true;
				int x = o.x;
				int y = o.y;
				if( ( wall & GWLiteCanvas.WALL_EAST ) != 0 )
				{
					x += o.width;
				}
				if( ( wall & GWLiteCanvas.WALL_SOUTH ) != 0 )
				{
					y += o.height;
				}
				if( ( wall & ( GWLiteCanvas.WALL_WEST | GWLiteCanvas.WALL_EAST ) ) == 0 )
				{
					x += o.width/2;
				}
				if( ( wall & ( GWLiteCanvas.WALL_NORTH | GWLiteCanvas.WALL_SOUTH ) ) == 0 )
				{
					y += o.height/2;
				}
				
				GWEntity explosion = new GWEntity( x, y, 0, 0, GWEntity.TYPE_EXPLOSION );
				gameState.layers[ gameState.layers.length - 2 ].addElement( explosion );
			}
			else
			{
				// adjust the velocity
				if( ( wall & (GWLiteCanvas.WALL_EAST | GWLiteCanvas.WALL_WEST) ) != 0 )
				{
					controllerData[1] = -controllerData[1];
				}
				if( ( wall & (GWLiteCanvas.WALL_SOUTH | GWLiteCanvas.WALL_NORTH) ) != 0 )
				{
					controllerData[2] = -controllerData[2];
				}
				dead = false;
			}
		}
		else
		{
			dead = false;
		}
		return dead;
	}

	public void learn(GWLiteCanvas gameState) 
	{
		// do nothing
	}

	public boolean collision(GWLiteCanvas gameState, GWEntity controlled, GWEntity with) 
	{
		boolean die; 
		if( this.bounce )
		{
			die = with.type == GWEntity.TYPE_BULLET;
			if( die )
			{
				gameState.explode( controlled, true );
			}
		}
		else
		{
			die = true;
		}
		
		return die;
	}

}
